package cn.iocoder.yudao.module.system.util.exam;

import cn.hutool.core.util.StrUtil;
import cn.iocoder.yudao.framework.common.util.http.HttpUtils;
import cn.iocoder.yudao.module.system.config.ExamTestProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 测评系统API客户端
 * 用于调用便捷数据网的测评API
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class ExamTestApiClient {

    @Resource
    private ExamTestProperties examTestProperties;

    // 便捷数据网测评API基础URL
    private static final String BASE_URL = "https://php.bian-jie.cn/interface/bjsj/api/exam";

    /**
     * 获取测评题列表
     *
     * @param tbl 测评类型标记值
     * @return API响应结果
     */
    public String getTestQuestions(String tbl) {
        String url = BASE_URL + "/list.php";

        Map<String, String> params = new HashMap<>();
        params.put("appKey", examTestProperties.getAppKeyByTbl(tbl));
        if (StrUtil.isNotBlank(tbl)) {
            params.put("tbl", tbl);
        }
        
        // 构建完整URL
        String fullUrl = buildUrlWithParams(url, params);
        
        log.info("调用测评题列表API: {}", fullUrl);
        
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            
            String response = HttpUtils.get(fullUrl, headers);
            log.info("获取测评题列表成功，响应长度: {}", response != null ? response.length() : 0);
            return response;
        } catch (Exception e) {
            log.error("调用测评题列表API失败", e);
            return null;
        }
    }

    /**
     * 获取测评相关信息
     *
     * @param tbl 测评类型标记值
     * @return API响应结果
     */
    public String getTestInfo(String tbl) {
        String url = BASE_URL + "/getExamInfo.php";

        Map<String, String> params = new HashMap<>();
        params.put("appKey", examTestProperties.getAppKeyByTbl(tbl));
        if (StrUtil.isNotBlank(tbl)) {
            params.put("tbl", tbl);
        }
        
        // 构建完整URL
        String fullUrl = buildUrlWithParams(url, params);
        
        log.info("调用测评信息API: {}", fullUrl);
        
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            
            String response = HttpUtils.get(fullUrl, headers);
            log.info("获取测评信息成功，响应长度: {}", response != null ? response.length() : 0);
            return response;
        } catch (Exception e) {
            log.error("调用测评信息API失败", e);
            return null;
        }
    }

    /**
     * 获取测评结果报告
     *
     * @param tbl 测评类型标记值
     * @param reportType 报告类型
     * @param answer 答案字符串
     * @param isAllAnswer 是否提交所有题目的答案
     * @return API响应结果
     */
    public String getTestReport(String tbl, String reportType, String answer, String isAllAnswer) {
        String url = BASE_URL + "/getReport.php";

        Map<String, String> params = new HashMap<>();
        params.put("appKey", examTestProperties.getAppKeyByTbl(tbl));
        if (StrUtil.isNotBlank(tbl)) {
            params.put("tbl", tbl);
        }
        if (StrUtil.isNotBlank(reportType)) {
            params.put("reportType", reportType);
        }
        params.put("answer", answer);
//        if (StrUtil.isNotBlank(isAllAnswer)) {
//            params.put("isAllAnswer", isAllAnswer);
//        }
//
        // 构建完整URL
        String fullUrl = buildUrlWithParams(url, params);
        
        log.info("调用测评报告API: {}", fullUrl);
        
        try {
            Map<String, String> headers = new HashMap<>();
            headers.put("Content-Type", "application/x-www-form-urlencoded");
            
            String response = HttpUtils.get(fullUrl, headers);
            log.info("获取测评报告成功，响应长度: {}", response != null ? response.length() : 0);
            return response;
        } catch (Exception e) {
            log.error("调用测评报告API失败", e);
            return null;
        }
    }

    /**
     * 构建带参数的URL
     *
     * @param baseUrl 基础URL
     * @param params 参数Map
     * @return 完整的URL
     */
    private String buildUrlWithParams(String baseUrl, Map<String, String> params) {
        if (params == null || params.isEmpty()) {
            return baseUrl;
        }

        StringBuilder urlBuilder = new StringBuilder(baseUrl);
        urlBuilder.append("?");

        boolean first = true;
        for (Map.Entry<String, String> entry : params.entrySet()) {
            if (!first) {
                urlBuilder.append("&");
            }

            String key = entry.getKey();
            String value = entry.getValue() != null ? entry.getValue() : "";

            // 只对花括号进行编码，其他字符保持原样
            String encodedValue = value.replace("{", "%7B").replace("}", "%7D");

            urlBuilder.append(key).append("=").append(encodedValue);
            first = false;
        }

        return urlBuilder.toString();
    }

}
